﻿#region The MIT License (MIT)
// The MIT License (MIT)
// Copyright (c) 2010 - 2013 Sovacode LLC
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Sovacode.DemoApp.Commands;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

/* Importing namespaces */
using Sovacode.DemoApp.Model;
using Sovacode.RubiksCube.Common.Managers.Validation;
using Sovacode.RubiksCube.Common.Model;

namespace Sovacode.DemoApp.ViewModel
{
    /// <summary>
    /// Class Serialization ViewModel
    /// </summary>
    public sealed class SerializationViewModel /*
                                                * 
                                                * Serialization demonstration of ObservableCollection<T>. The native ObservableCollection<T> can not be serialized, but here
                                                * you can find workaround of this issue.
                                                * 
                                                */
        : BasicViewModel.ChildsHolderViewModel
    {
        #region Private Fields

        /// <summary>
        /// The file name
        /// </summary>
        private string _fileName = string.Empty;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets the name of the file.
        /// </summary>
        /// <value>The name of the file.</value>
        public string FileName
        {
            get { return _fileName; }
            set
            {
                _fileName = value;

                OnPropertyChanged(() => FileName);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Saves the data objects.
        /// </summary>
        private void SaveDataObjects()
        {
            try
            {
                using (Stream stream = File.Open(FileName, FileMode.Create))
                {
                    /* Saving collection */
                    new BinaryFormatter().Serialize(stream, DataObjects);
                }
            } catch (IOException e)
            {
                ShowError(e.Message);
            }
        }

        /// <summary>
        /// Loads the data objects.
        /// </summary>
        private void LoadDataObjects()
        {
            try
            {
                using (Stream stream = File.Open(FileName, FileMode.Open))
                {
                    /* Restoring collection */
                    var restoredList = ((ICollection<SimpleDataObject>) new BinaryFormatter().Deserialize(stream));

                    DataObjects.Clear();

                    foreach (SimpleDataObject dataObject in restoredList)
                    {
                        DataObjects.Add(dataObject);
                    }
                }
            } catch (IOException e)
            {
                ShowError(e.Message);
            }
        }

        /// <summary>
        /// Determines whether is valid filename.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns><c>true</c> if valid filename; otherwise, <c>false</c>.</returns>
        private bool IsValidFilename(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return false;
            }

            if ((from invalidPathChar in Path.GetInvalidFileNameChars() from c in fileName.ToCharArray() where c == invalidPathChar select invalidPathChar).Any())
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Determines whether is valid specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns><c>true</c> if is valid specified path; otherwise, <c>false</c>.</returns>
        private bool IsValidPathname(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return false;
            }

            if ((from invalidPathChar in Path.GetInvalidPathChars() from c in path.ToCharArray() where c == invalidPathChar select invalidPathChar).Any())
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Checks for correct IO path.
        /// </summary>
        /// <returns><c>true</c> if file name or path is correct, <c>false</c> otherwise</returns>
        private bool CheckForCorrectPath()
        {
            if (string.IsNullOrWhiteSpace(FileName))
            {
                return false;
            }

            if (!IsValidPathname(Path.GetDirectoryName(FileName)))
            {
                return false;
            }

            if (!IsValidFilename(Path.GetFileName(FileName)))
            {
                return false;
            }

            return true;
        }

        #endregion

        #region Override

        /// <summary>
        /// Method where the commands should be registered.
        /// </summary>
        protected override void RegisterCommands()
        {
            base.RegisterCommands();

            RegisterCommand(Const.SerializationView.LoadDataObjects, o => LoadDataObjects(), p => File.Exists(FileName));
            RegisterCommand(Const.SerializationView.SaveDataObjects, o => SaveDataObjects(), p => CheckForCorrectPath());
        }

        /// <summary>
        /// Registration of <see cref="ValidationRule" /> begins here. You should use it in all objects with validation.
        /// </summary>
        protected override void RegisterValidationRules()
        {
            base.RegisterValidationRules();

            RegisterRule(() => FileName, () => !string.IsNullOrWhiteSpace(FileName) && CheckForCorrectPath(), "File name empty or invalid!");
        }

        /// <summary>
        /// Gets the description file.
        /// </summary>
        /// <value>The description file.</value>
        protected override string DescriptionFile
        {
            get { return "SerializationDescription.txt"; }
        }

        #endregion

    }
}